package com.jddup.program.dao.sqlbuilder.mysql;

import com.jddup.common.pojo.TableColumn;
import com.jddup.common.pojo.TableMeta;
import com.jddup.program.dao.sqlbuilder.UpdatePrepareSQLBuilder;

import java.util.List;

/**
 * Created by ZZB on 2017/10/19.
 */
public class MysqlUpdatePrepareSQLBuilder implements UpdatePrepareSQLBuilder {
	private final static String UPDATE_SQL = "update {tableName} set {columns} where {pk} = ?;";
	private final static String UPDATE_FIELD_SQL = "update {tableName} set {column} = ? where {pk} = ?;";
	private final static String UPDATE_LIST_FIELD_SQL = "update {tableName} set {column} = ? where {pk} in ({pks});";

	@Override
	public String buildUpdateSQL(TableMeta tableMeta) {
		String tableName = tableMeta.getTableName();
		List<TableColumn> tableColumns = tableMeta.getTableColumns();
		if (tableColumns.size() == 0) {
			return "";
		}
		String columns = tableColumns.stream().filter(
				tableColumn -> !tableColumn.getColumnName().equals(tableMeta.getPrimaryKeyColumn().getColumnName()))
				.map(tableColumn -> "`" + tableColumn.getColumnName() + "` = ?").reduce((s, s2) -> s + "," + s2).get();
		return UPDATE_SQL.replace("{tableName}", tableName).replace("{columns}", columns).replace("{pk}",
				"`" + tableMeta.getPrimaryKeyColumn().getColumnName() + "`");
	}

	@Override
	public String buildUpdateFieldSQL(TableMeta tableMeta, String column, Object value, Object pk) {
		return UPDATE_FIELD_SQL.replace("{tableName}", tableMeta.getTableName()).replace("{column}", "`" + column + "`")
				.replace("{pk}", "`" + tableMeta.getPrimaryKeyColumn().getColumnName() + "`");
	}

	@Override
	public String buildUpdateListFieldSQL(TableMeta tableMeta, String column, Object value, List<?> pks) {
		return UPDATE_LIST_FIELD_SQL.replace("{tableName}", tableMeta.getTableName())
				.replace("{column}", "`" + column + "`")
				.replace("{pk}", "`" + tableMeta.getPrimaryKeyColumn().getColumnName() + "`")
				.replace("{pks}", pks.stream().map(o -> "?").reduce((s, s2) -> s + "," + s2).get());
	}
}
